﻿using System;
using ITViet.Services;
using ITViet.Web.App_Code;

namespace ITViet.Web.Admin
{
  public partial class AccountInfo : AdminBasePage
  {
    internal override int RequiredPermission
    {
      get
      {
        return 0;
      }
    }

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        ShowAccountInfo();
      }
    }

    protected void ctrCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "ChangePassword")
      {
        e.Result = ChangePassword();
      }
      else if (para[0] == "Save")
      {
        e.Result = SaveInfo();
      }
    }

    #endregion

    #region Methods
    private void ShowAccountInfo()
    {
      if (CurrentUser != null)
      {
        lblUsername.Text = CurrentUser.Username;
        txtFullName.Text = CurrentUser.Fullname;
        txtEmail.Text = CurrentUser.Email;
      }
    }

    private string ChangePassword()
    {
      try
      {
        if (CurrentUser != null)
        {
          string oldPassword = Library.Encryption.MD5.Encrypt(txtOldPass.Text);

          //Not enter correct current password
          if (oldPassword != CurrentUser.Password)
            return Resources.Messages.ERR0013;

          //NewPassword and OldPassword are the same
          string newPassword = Library.Encryption.MD5.Encrypt(txtNewPass.Text);
          if (oldPassword == newPassword)
            return Resources.Messages.ERR0014;

          //ConfirmPassword is different from NewPassword
          string confirmPassword = Library.Encryption.MD5.Encrypt(txtConfirmPass.Text);
          if (newPassword != confirmPassword)
            return Resources.Messages.ERR0015;

          CurrentUser.Password = newPassword;
          new UserService().Save(CurrentUser);
          ((AdminBasePage)Page).CurrentUser = CurrentUser;
        }
      }
      catch (Exception ex)
      {
        WriteLog("AccountInfo.aspx::Change Password", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty; ;
    }

    private string SaveInfo()
    {
      try
      {
        CurrentUser.Fullname = txtFullName.Text;
        CurrentUser.Email = txtEmail.Text;
        new UserService().Save(CurrentUser);
        ((AdminBasePage)Page).CurrentUser = CurrentUser;
      }
      catch (Exception ex)
      {
        WriteLog("AccountInfo.aspx::Save Info", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
    #endregion

  }
}
